var app = getApp();
var utils = require('../../utils/util.js');
Page({
    data: {
        startX: 0, //开始坐标
        startY: 0,
        istips: false,
        totalPrice: 0,
        selectedAll: true
    },

    onShow: function(e) {
        var that = this;
        that.systemInfo(function() {
            that.personalInfo();
            that.getNewCartInfo();
            that.checkAllCart();
        });

    },
    //从后端获取最新的购物车中的商品信息
    getNewCartInfo: function() {
        var that = this;
        var specArr = [];
        var cartlist = wx.getStorageSync("cartInfo");
        if (!cartlist) return false;
        cartlist.forEach((value, key) => {
            if (value) specArr.push(value.spec_id);
        });
        utils.http("/api/v1/cart/cart_check_db", {
            spec_id_str: specArr
        }, function(res) {
            var response = res.datas;
            var vo = [];
            for (var key in cartlist) {
                for (var index in response) {
                    if (!cartlist[key]) continue;
                    if (cartlist[key].spec_id == response[index].cart_spec.id) {
                        if (!response[index].id) continue;
                        vo[index] = {
                            name: response[index].name,
                            image: response[index].image,
                            subtitle: response[index].subtitle,
                            spec_price: response[index].cart_spec.spec_price,
                            spec_vip_price: response[index].cart_spec.spec_vip_price,
                            spec_stock: response[index].cart_spec.spec_stock,
                            spec_name: response[index].cart_spec.spec_name,
                            id: response[index].id,
                            spec_id: cartlist[key].spec_id,
                            number: cartlist[key].number <= response[index].cart_spec.spec_stock ? cartlist[key].number : response[index].cart_spec.spec_stock,
                            selectStatus: cartlist[key].selectStatus,
                        };
                        continue;
                    }
                }
            }
            console.log('后台跟缓存混合后的数据', vo)
            that.setData({
                items: vo,
            }, function() {
                wx.setStorageSync('cartInfo', vo)
                utils.setTabBarBadge();
                that.allNumber();
            });
        });
    },
    //判断状态是否全选  如果有一个没有选择就不会全选  
    checkAllCart: function() {
        var that = this;
        var carlist = wx.getStorageSync("cartInfo");
        if (carlist.length != 0) {
            for (var i = 0; i < carlist.length; i++) {
                if (!carlist[i]) continue;
                if (carlist[i].selectStatus != true) {
                    that.setData({
                        selectedAll: false
                    });
                    break;
                } else {
                    that.setData({
                        selectedAll: true
                    });
                }
            };
        }
    },
    //我的个人信息
    personalInfo: function(e) {
        var that = this;
        utils.showLoading();
        utils.http("/api/v1/member/index", {}, function(res) {
            utils.hideLoading();
            that.setData({
                info: res.datas,
            }, () => {
                that.allNumber();
            });
        });
    },
    //基本数据
    systemInfo: function(callback = '') {
        var that = this;
        utils.showLoading();
        utils.http("/api/v1/common/system", {}, function(res) {
            utils.hideLoading();
            that.setData({
                system: res.datas
            }, function() {
                typeof callback == 'function' ? callback() : '';
            })
        })
    },

    //封装全局数量的加减
    allNumber: function(e) {
        var that = this;
        var price = 0;
        var totalPrice = 0;
        var itemslist = that.data.items;
        for (var i in itemslist) {
            price = that.data.info.is_vip == 0 ? itemslist[i].spec_price : itemslist[i].spec_vip_price;
            if (itemslist[i].selectStatus == true) {
                totalPrice = totalPrice + (parseInt(itemslist[i].number) * parseFloat(price));
            }
        }
        that.setData({
            totalPrice: totalPrice.toFixed(2)
        })
        console.log(itemslist)
        console.log('++++++++', totalPrice, that.data.system.start_price)
        if (totalPrice >= that.data.system.start_price) {
            console.log('>>>>>')
            that.setData({
                istips: true
            })
        } else {
            var chaNum = that.data.system.start_price - totalPrice;
            that.setData({
                istips: false,
                chaNum: chaNum
            })
        }
    },
    //授权登陆
    bindGetUserInfo: function(e) {
        var that = this;
        console.log(e)
        if (e.detail.errMsg == "getUserInfo:ok") {
            var data = {
                nickname: e.detail.userInfo.nickName,
                sex: e.detail.userInfo.gender,
                avatar: e.detail.userInfo.avatarUrl
            }
            app.memberModify(data);
            that.personalInfo();
        }
    },
    //单选结算
    toggleSelect: function(e) {
        var that = this;
        var itemslist = that.data.items;
        var index = e.currentTarget.dataset.index;
        itemslist[index].selectStatus = !itemslist[index].selectStatus;
        that.setData({
            items: itemslist
        })
        wx.setStorageSync("cartInfo", itemslist)
        that.allNumber();
        that.checkAllCart();
    },
    //全选
    toggleSelectAll: function(e) {
        var that = this;
        var itemslist = that.data.items;
        that.data.selectedAll = !that.data.selectedAll
        that.setData({
            selectedAll: that.data.selectedAll
        })
        if (that.data.selectedAll == true) {
            for (var i in itemslist) {
                itemslist[i].selectStatus = true;
            }
            that.allNumber();
        } else {
            for (var i in itemslist) {
                itemslist[i].selectStatus = false;
            }
            that.allNumber();
        }
        that.setData({
            items: itemslist
        })
        wx.setStorageSync("cartInfo", itemslist);
    },
    //减数量
    onNextTap: function(e) {
        var that = this;
        var itemslist = that.data.items;
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.number;
        if (num > 1) {
            itemslist[index].number = num - 1;
			// wx.setStorageSync("number", wx.getStorageSync("number") - 1)
			wx.setStorage({
				key: "number",
				data: wx.getStorageSync("number") - 1,
				success:function(){
					utils.setTabBarBadge();
				},
			})
        } else {
            utils.message("该宝贝宝贝不能减少哦~")
        }

        that.setData({
            items: itemslist
        })
        wx.setStorageSync("cartInfo", that.data.items)
        that.allNumber();
    },
    //加数量
    onPrevTap: function(e) {
        var that = this;
        var itemslist = that.data.items;
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.number;
        itemslist[index].number = num + 1;
		wx.setStorage({
			key: "number",
			data: wx.getStorageSync("number") + 1,
			success: function () {
				utils.setTabBarBadge();
			},
		})
        that.setData({
            items: itemslist
        })
        wx.setStorageSync("cartInfo", that.data.items)
        that.allNumber();
    },
    //去凑单跳入onClassIfyTap  分类页面
    onClassIfyTap: function(e) {
        wx.switchTab({
            url: '../classify/classify',
        })
    },
    //立即购买
    buyNowTap: function(e) {
        wx.setStorageSync("type", 0)
        wx.navigateTo({
            url: '../confirmorder/confirmorder?type=0'
        })
    },

    //手指触摸动作开始 记录起点X坐标
    touchstart: function(e) {
        //开始触摸时 重置所有删除
        this.data.items.forEach(function(v, i) {
            if (v.isTouchMove) //只操作为true的
                v.isTouchMove = false;
        })
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            items: this.data.items
        })
    },
    //滑动事件处理
    touchmove: function(e) {
        var that = this,
            index = e.currentTarget.dataset.index, //当前索引
            startX = that.data.startX, //开始X坐标
            startY = that.data.startY, //开始Y坐标
            touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
            touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
            //获取滑动角度
            angle = that.angle({
                X: startX,
                Y: startY
            }, {
                X: touchMoveX,
                Y: touchMoveY
            });
        that.data.items.forEach(function(v, i) {
            v.isTouchMove = false
            //滑动超过30度角 return
            if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX) //右滑
                    v.isTouchMove = false
                else //左滑
                    v.isTouchMove = true
            }
        })
        //更新数据
        that.setData({
            items: that.data.items
        })
    },

    /**
     * 计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle: function(start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    //删除事件
    del: function(e) {
        var index = e.currentTarget.dataset.index;
        var bynber = wx.getStorageSync("number") - this.data.items[index].number
        wx.setStorageSync("number", bynber)
        this.data.items.splice(index, 1);
        this.setData({
            items: this.data.items
        })

        wx.setStorageSync("cartInfo", this.data.items)
        utils.setTabBarBadge();
    },
})